//取小数位
function getDecimalPart(num) {
  let str = '';
  if (typeof num == 'number') {
    str = num.toFixed(2).toString();
  } else {
    str = num;
  }
  const parts = str.split('.');
  return parts[1] || '';
}

function addThousandSeparator(num) {
  let str = '';
  let decimalpart = getDecimalPart(num);
  if (typeof num == 'number') {
    if (num < 0) {
      //将数字绝对值化
      let num1 = num * -1;
      // str = num1.toFixed(0).toString();
      //获取整数位
      str = Math.floor(num1).toString();
    } else if (num == 0) {
      str = '0';
    } else {
      str = Math.floor(num).toString();
    }
  } else {
    str = num;
  }
  const parts = str.split('').reverse();
  let result = [];
  let thousand = 0;
  for (let i = 0; i < parts.length; i++) {
    if (i > 0 && i % 3 === 0) {
      result.push(',');
    }
    result.push(parts[i]);
  }

  let returnstr = result.reverse().join('');
  if (decimalpart) {
    returnstr = returnstr + '.' + decimalpart;
  }
  if (num < 0) {
    returnstr = '-' + returnstr;
  }
  return returnstr;
}

export { addThousandSeparator };
